port = "8080"  ' 目标端口号

' 执行命令获取端口-PID映射
Set objShell = CreateObject("WScript.Shell")
Set exec = objShell.Exec("cmd /c netstat -ano | findstr  " & port)
' WScript.Echo "netstat -ano | findstr :" & port
' 解析PID
pid = ""

' 用正则表达式提取PID
Set regex = New RegExp
regex.Pattern = "\d+$"  ' 匹配行末的数字（即PID）
pidList = ""           ' 存储所有找到的PID


' 读取标准输出
Do While Not exec.StdOut.AtEndOfStream
    line = exec.StdOut.ReadLine()' 逐行读取并拼接结果
    If InStr(line, "LISTENING") > 0 Then
        Set matches = regex.Execute(line)
        If matches.Count > 0 Then
            pid = matches(0).Value
            pidList = pidList & pid & vbCrLf
        End If
    End If
Loop

' 终止进程或提示结果
If pidList <> "" Then
    For Each pid In Split(pidList, vbCrLf)
        If pid <> "" Then
            objShell.Run "taskkill /f /pid " & pid, 0, True
            WScript.Echo "Find AiBox Server, kill PID: " & pid & " ,Restarting!"
        End If
    Next
Else
    WScript.Echo "Starting"
End If




' 终止进程
' If pid <> "" Then
'     objShell.Run "taskkill /f /pid " & pid, 0, True
'     WScript.Echo "kill PID " & pid & " process"
' Else
'     WScript.Echo "port " & port & " have no process"
' End If

Set ws = CreateObject("Wscript.Shell")
ws.run "cmd /c title AiBox & F:\torch\aibox\start_server.bat", 7, True
